package com.hmall.search.utils;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import java.util.ArrayList;
import java.util.List;

/**
 * 聚合工具类
 *
 * @Author XiaoJiangShi
 * @Date 2022/8/11 14:48
 * @Blog blog.XiaoJiangShi.net/996.mba
 * @Description: 聚合工具类
 */
public class AggFiltersUtil {

    /**
     * 桶聚合条件
     *
     * @param request   searchRequest 对象
     * @param aggName   聚合名称
     * @param fieldName 聚合字段
     * @param size      获取条数
     */
    public static void getByAggName(SearchRequest request, String aggName, String fieldName, Integer size) {
        request.source().size(0)
                .aggregation(
                        AggregationBuilders.terms(aggName)
                                .field(fieldName)
                                .size(size)
                );
    }

    /**
     * 根据聚合名称解析结果
     * @param response 响应消息对象
     * @param aggName 聚合名称
     * @return 结果集
     */
    public static List<String> getResultByAggName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }

        return list;
    }
}

